/*
 * Copyright (C) 2017 Fromentin Xavier
 *
 * This file is part of GDOB.
 *
 * GDOB is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * GDOB is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.grimdawnofflinebuilder.util

import com.grimdawnofflinebuilder.util.config.GDOBConfig
import com.grimdawnofflinebuilder.util.tex.TexConverter
import java.io.File
import kotlin.system.measureTimeMillis

class ResourceUtil {

    companion object {

        /**
         * Extract and convert all needed images from Grim Dawn arc files
         */
        //TODO XFR : extract from all needed arc not just UI
        fun extractAndConvertImages() {
            val pref = GDOBConfig.preferences
            val processBuilder = ProcessBuilder( """${pref.grimDawnDir}\ArchiveTool""",
                                                 """${pref.grimDawnDir}\resources\UI.arc""", "-extract",
                                                 pref.installDir )
            processBuilder.redirectOutput( ProcessBuilder.Redirect.INHERIT )
            processBuilder.redirectError( ProcessBuilder.Redirect.INHERIT )
            val process = processBuilder.start()
            val exitValue = process.waitFor()
            if( exitValue != 0 )
                println( "An error occured during images extraction" )
            var fileCpt = 0
            val convertTime = measureTimeMillis {
                val fileWalker = File( """${pref.installDir}\ui""" ).walk()
                val texConverter = TexConverter()
                fileWalker.filter { it.extension == "tex" }
                  .forEach {
                      texConverter.convertTexToPng( it )
                      fileCpt++
                  }
            }
            println( "Converted $fileCpt files in ${convertTime / 1000} seconds." )
        }

    }

}

fun main( args: Array<String> ) {
    ResourceUtil.extractAndConvertImages()
}